﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace GraphicLib
{
    public class VarianceCalculator
    {
        /// <summary>
        /// 得到像素数组的方差
        /// </summary>
        /// <param name="doubles"></param>
        /// <returns></returns>
        public static double GetVariance(byte[] bytes)
        {
            double variance = 0;
            double stdVariance = 0;
            double pixelCount = 1;
            double grayAverage = 0;
            double graySum = 0;
            try
            {
                pixelCount = bytes.Count();
                for (int i = 0; i < pixelCount; i++)
                {
                    graySum += bytes[i];
                }
                grayAverage = graySum / pixelCount;
                double diffValueSum = 0;
                //累计与平均值的上下差异的绝对值 判断标准方差正负号
                //double negValue = 0;
                //double posValue = 0;
                for (int j = 0; j < pixelCount; j++)
                {
                    diffValueSum += Math.Pow(bytes[j] - grayAverage, 2);
                    //if (doubles[j] >= grayAverage)
                    //{
                    //    posValue += Math.Abs(doubles[j] - grayAverage);
                    //}
                    //else
                    //{
                    //    negValue += Math.Abs(doubles[j] - grayAverage);
                    //}
                }
                variance = diffValueSum / pixelCount;
                stdVariance = Math.Pow(variance, 0.5);
                //if (posValue < negValue)
                //{
                //    stdVariance = -stdVariance;
                //}
                
            }
            catch (Exception ex)
            {
                File.AppendAllText(Sample.LOG_PATH, ex.ToString() + "\r\n");
            }
            return stdVariance;
        }
        public static double GetProductVariance(byte[] bytes)
        {
            return GetVariance(bytes);
        }
    }
}
